/*
 *@author: YangJie
 *@date: 2021-04-07 16:48:13
 *@version:
 *@description:维修保养=>故障报修
 */
 import React, { Component } from 'react';
 import { Table, Button, Form, Tabs ,Input , TreeSelect ,Select,Row,Col, Modal } from 'antd';
 import '@/assets/css/settings';
 import * as Utils from '../../utils_yyr/action';
 import { withRouter } from 'react-router-dom';
import Paging from '../../components_yyr/commponent/Paging';
import { euqApplicationName, lotAuth, lotAuth2 } from '../../config';
 import moment from 'moment';
 import 'moment/locale/zh-cn';
 moment.locale('zh-cn')
 
 const nowDate = Utils.getNowDate()
 const { TabPane } = Tabs;
 const {TreeNode} = TreeSelect
 const {Option} = Select
 const { TextArea } = Input
 
 class App extends Component {
	 state = {
		 loading: false, //加载中...
		 dataSource: [], //数据源
		 dataSource1: [],
		 drawerVisible: false, //新增修改抽屉的显示与隐藏
		 chooseData: {},
		 drawerTitle: '',
		 total: 0,
		 formValues: {},
		 cityData: [],
		 mainFactoryList: [],
		 selectedData: [],
		 selectedKeys: [],
		 handleType:0,
		 EquTypePageList:[],
		 DepartmentList:[],//部门列表
		 UserList:[],//用户查询
		 jjcd:[],//紧急程度列表
		 wxz:[],
		 visibleEqu :false,
		 loadingTable: false,
		 tableData: [],
		 totalTable:0,
		 formValuesTable:{},
		 selectedDataTable: [],
		 status:0,
		 selectedKeysTable: [],
		 value:1,
		 wxlb:[],
		 zydw:[],
		 wldw:[],
		 visiblePeo:false,
		 equipmentRepairWorkAddDTOList:[],
		 switchChecked:false,
		 selectedDataTable: [],
		 selectedKeysTable:[],
		 totalTablePeo:0,
		 formValuesTablePeo:{},
		 peopleData:[],
		 UserList:[],//用户查询
		 id:'',
		 obj:{}
	 };
	 componentDidMount() {
		 this.fetch({
			typeId:2
		});
		let loc = window.location.href.split('/');
		// console.log(id)
		let str = loc[loc.length-1].split('?')
		let id = str[0]
		this.get(euqApplicationName + '/equipmentInfo/findEqu?equId='+id).then(res=>{
			console.log(res.data)
			this.setState({obj : res.data ? res.data : {}})
		})
		//  this.EquTypePageList()
		//  this.queryTreeDepartment()
		//  this.queryPageUser()
		//  this.jjcd()
		//  this.wxz()
		//  this.wxlb()
		//  this.zydw()
		//  this.wldw()
	 }
	 //初始化加载数据
	 fetch = (data) => {
		let loc = window.location.href.split('/');
		let str = loc[loc.length-1].split('?')
		let id = str[0]
		this.setState({id})
	 };
	 zydw = () => {//租用单位列表
		this.get(euqApplicationName + '/parameter_setting_public/queryRentDepartmentList?type=2').then(res => {
			this.setState({
				zydw: res.data,
			});
		})
	   }
	
	   wldw = () => {//往来单位列表
		this.get(euqApplicationName + '/parameter_setting_public/queryRentDepartmentList?type=1').then(res => {
			this.setState({
				wldw: res.data,
			});
		})
	   }	
	   
	//   用户查询
	queryPageUser = () => {
		this.get(lotAuth2 + '/user/queryPageUser').then(res => {
			this.setState({
				UserList : res.data.data
			});
		})
	}

	 // 部门查询
	 queryTreeDepartment = () => {
	// 	 this.get(lotAuth + '/department/queryTreeDepartment').then(res => {
		 this.get(lotAuth2 + '/department/queryTreeDepartment').then(res => {
			 this.setState({
				 DepartmentList: res.data
			 });
		 })
	 }
 
	 EquTypePageList = () => {
		 this.get(euqApplicationName + '/parameter_setting_equipmentType/findEquTypePageList').then(res1 => {
			 this.setState({
				 EquTypePageList : res1.data
			 });
		 })
	 }
	 wxz = () => {//维修组
		this.get(euqApplicationName + '/parameter_setting_public/queryTeamPageList?type=维修').then(res => {
		this.setState({
			 wxz: res.data,
		 });
		 })
	}; 
	jjcd = () => {//紧急程度列表
	   this.get(euqApplicationName + '/api/findEquipmentNextParameterPageList?typeId=8').then(res => {
	   this.setState({
		 jjcd: res.data,
		});
		})
   }; 
	wxlb = () => {//维修类别列表
	 this.get(euqApplicationName + '/api/findEquipmentNextParameterPageList?typeId=7').then(res => {
	 this.setState({
		wxlb: res.data,
	  });
	  })
 	}; 
	 
	 lastOperateIsChoose = () => {
		 console.log(this.state.equipmentRepairWorkAddDTOList)
		 const p = this
		 this.handleSubmit()
	 }
 
	 // 提交modal
	 // 提交modal
	 handleSubmit = () => {
		const {equipmentRepairWorkAddDTOList,id} = this.state;
		let str = ''
		for(var item of equipmentRepairWorkAddDTOList){
			str += item.id + ','
		}
		
		// this.get(euqApplicationName + `/equipmentRepairFault/deleteEquipmentRepairFaultList?ids=${str.slice(0, str.length - 1)}`)
		this.post(euqApplicationName + '/equipmentInfo/addSubset', { data : {ids:str.slice(0, str.length - 1),pid:Number(id)} }).then(res => {
			this.success();
			this.props.history.push('/EquipmentList')
		});
		 
	 };
 
 
	 onTreeChange = () => { };
 
	 renderTreeNodes = (data, name, valueField) =>
	 // console.log(data, name, valueField)
		 data && data.map(item => {
			 if (item.children) {
				 return (
					 <TreeNode title={item[name]} key={item[valueField]} value={item[valueField]} dataRef={item}>
						 {this.renderTreeNodes(item.children, name, valueField)}
					 </TreeNode>
				 );
			 }
			 return <TreeNode key={item[valueField]} value={item[valueField]} title={item[name]} {...item} />;
		 });
 
	 chooseEqu = () => {
		 this.fetchTable({
			 pageNum: 1,
			 pageSize: 10
		 })
		 this.setState({visibleEqu : true})
	 }
	 choosePeo = () => {
		this.fetchTablePeo({
			pageNum: 1,
			pageSize: 10
		})
		this.setState({visiblePeo : true})
	}
 
	fetchTable = (data) => {
		 let str = ''
		 for(var key in data){
			 if(data[key]){
				 str += `&${key}=${data[key]}`
			 }
		 }
		 this.setState({ loadingTable: true })
		 this.get(euqApplicationName + '/equipmentInfo/findEquInfoList?'+str).then(res => {
			let deleteAfterArr = res.data.data.filter(item => item.id != this.state.id)
			this.setState({
				loadingTable: false,
				tableData:deleteAfterArr,
				totalTable:res.data.total - 1,
				formValuesTable:data,
				selectedKeysTable:[],
				selectedDataTable:[],
			});
		})
	}
	 fetchTablePeo = (data) => {
		let str = ''
		for(var key in data){
			if(data[key]){
				str += `&${key}=${data[key]}`
			}
		}
		this.setState({loadingTable:true})
		this.get(euqApplicationName + '/equipmentMaintain/findUserOfMaintain?'+str).then(res => {
			this.setState({
				loadingTable:false,
				peopleData: res.data,
				totalTablePeo:res.total,
				formValuesTablePeo:data,
				selectedKeysTablePeo:[],
				selectedDataTablePeo:[],
			});
		})
	}
 
	 closeModal = () => {
		 this.setState({visibleEqu:false,visiblePeo:false})
	 }
 
	 modalSubmit = () => {
		 if(this.state.selectedKeysTable.length!==1){
			 Utils.openNotification('warning','请（仅）选择一条数据！')
			 return;
		 }
		 let data = this.state.selectedDataTable[0]
		 // 'equCode', 'equName','equType','equSpecsModel','deptId','equPosition'
		 this.props.form.setFieldsValue({
			 equCode : data.equCode,
			 equName : data.equName,
			 equType : data.equTypeId,
			 equSpecsModel : data.equSpecsModel,
			 deptId : data.depId,
			 equPosition : data.equipmentLocation,
		 })
		 this.closeModal()
	 }
	  
	 modalSubmitPeo = () => {
		if(this.state.selectedKeysTable.length===0){
			Utils.openNotification('warning','请选择数据！')
			return;
		}
		let {equipmentRepairWorkAddDTOList} = this.state
		let data = this.state.selectedDataTable
		for(var item of data){
			item.personId = item.id
			item.personName = item.userName
		}
		// 'repairStartTime' ,'repairEndTime' ,'wastedTime' ,'contentOrSteps',
		let newData = [...equipmentRepairWorkAddDTOList];
		console.log(newData)
		const ids = newData.map(item => item.id);
		data.forEach(item => {
			ids.indexOf(item.id) === -1 && newData.push({
				equCode: item.equCode,
				equName: item.equName,
				equSpecsModel: item.equSpecsModel,
				userDepartment: item.userDepartment,
				equLocation: item.equLocation,
				equTypeId: item.equTypeId,
				id: item.id,
			});
		});
		console.log(newData)
		this.setState({
			equipmentRepairWorkAddDTOList:newData
		})
		this.closeModal()
	}
	 TableSearch = () => {
		 this.props.form.validateFields(['depId','equTypeId'],(err,values)=>{
			 if(!err){
				 console.log(values)
				 values.pageNum = this.state.formValuesTable.pageNum;
				 values.pageSize = this.state.formValuesTable.pageSize;
				 this.fetchTable(values);
			 }
		 })
	 }
	 TableSearchPeo = () => {
		this.props.form.validateFields(['department','userName'],(err,values)=>{
			if(!err){
				console.log(values)
				values.pageNum = this.state.formValuesTable.pageNum;
				values.pageSize = this.state.formValuesTable.pageSize;
				this.fetchTablePeo(values);
			}
		})
	}
 
		input1 = (e,record,index) => {
		   let {equipmentRepairWorkAddDTOList} = this.state
		   record.equLocation = e.target.value
		   console.log(e.target.value,record,index)
		}
		handleDelete = key => {
			const equipmentRepairWorkAddDTOList = [...this.state.equipmentRepairWorkAddDTOList];
			this.setState({ equipmentRepairWorkAddDTOList: equipmentRepairWorkAddDTOList.filter(item => item.id !== key) });
		};
		SwitchOnChange = (checked) => {
			this.setState({switchChecked:checked})
		}
	 render() {
		 const columns = [
			 {
				 title: '删除', width: 80, 
				 render: (text, record) => {
					 return <span><a href onClick={() => this.handleDelete(record.id)}>删除</a></span>
				 }
			 },
			 { title: '设备编号', width: 150, dataIndex: 'equCode' },
			 { title: '设备名称', width: 150, dataIndex: 'equName'},
			 { title: '规格型号', width: 150, dataIndex: 'equSpecsModel' },
			 { title: '所在部门', width: 200, dataIndex: 'userDepartment' },
		 ];
 
		 const column = [
			 { title: '设备编码', width: 150, dataIndex: 'equCode' },
			 { title: '设备名称', width: 150, dataIndex: 'equName' },
			 { title: '规格型号', width: 150, dataIndex: 'equSpecsModel' },
			 { title: '使用部门', width: 150, dataIndex: 'userDepartment' },
			 { title: '设备类别', width: 150, dataIndex: 'equTypeName' },
			 { title: '设备位置', width: 150, dataIndex: 'equipmentLocation' },
		 ]
		 const columnPeo = [
			{ title: '名称', width: 150, dataIndex: 'userName' },
			{ title: '职务', width: 150, dataIndex: 'roleName' },
			{ title: '使用部门', width: 150, dataIndex: 'department' },
			{ title: '执行班组', width: 150, dataIndex: 'teamName' },
		 ]
		 const {  loading,visibleEqu ,totalTable ,formValuesTable ,loadingTable ,selectedKeysTable ,visiblePeo ,equipmentRepairWorkAddDTOList,selectedKeysTablePeo,selectedDataTablePeo,formValuesTablePeo,totalTablePeo,peopleData,obj} = this.state;
		 const {  EquTypePageList ,gzdj ,gzlb , DepartmentList , jjcd ,wxz ,wxjb ,wxlb,wxzt,gzyy , zydw , wldw,UserList} = this.state;
 
		 //选择框
		 const rowSelectionTablePeo = {
			 selectedRowKeys: selectedKeysTablePeo,
			 onChange: (selectedRowKeys, selectedRows) => {
				 this.setState({
					 selectedDataTablePeo: selectedRows,
					 selectedKeysTablePeo: selectedRowKeys
				 })
			 },
		 };
 
		 const rowSelectionTable = {
			 selectedRowKeys: selectedKeysTable,
			 onChange: (selectedRowKeys, selectedRows) => {
				 this.setState({
					 selectedDataTable: selectedRows,
					 selectedKeysTable: selectedRowKeys
				 })
			 },
		 }
		 const { getFieldDecorator}=this.props.form
		 const p = this
		 const modalProps = {
			 title:"选择设备",
			 visible:visibleEqu,
			 width : '780px',
			 onCancel() {
			   p.closeModal();
			 },
			 okText:'保存',
			 cancelText:'取消',
			 onOk(){
			   p.modalSubmitPeo();
			 }
		   };
		const wwdw = zydw.concat(wldw)
		 return (
			<div className="shadow-radius">
				<Modal {...modalProps}>
					<Form  {... {labelCol: {xs: { span: 30 },sm: { span:6 },},wrapperCol: {xs: {span: 24},sm: {span: 14}}}}>
					<Row gutter={24}>
						<Col span={10}>
								<Form.Item label="设备类别">
									{getFieldDecorator('equTypeId')(
										<TreeSelect onChange={this.onTreeChange} placeholder={'请选择设备类别'} showCheckedStrategy="SHOW_PARENT" treeCheckable={false}  allowClear>
										{this.renderTreeNodes(EquTypePageList, 'name', 'id')}
										</TreeSelect>)}
								</Form.Item>
						</Col>
						<Col span={10}>
								<Form.Item label="所在部门">
									{getFieldDecorator('depId',)(
										<Select allowClear placeholder='请输入所在部门'>
												{DepartmentList.map(item=><Option value={item.id}>{item.name}</Option>)}
										</Select>)}
								</Form.Item>
						</Col>
						<Col span={4}>
							<Button type="primary" onClick={()=>{this.TableSearch()}}>查询</Button>
						</Col>
					</Row>
					</Form>	
						<Table columns={column} dataSource={p.state.tableData} pagination={false} loading={loadingTable}  rowSelection={rowSelectionTable} rowKey={(record, index) => record.id} childrenColumnName={''}/>
						<Paging total={totalTable} formValues={formValuesTable} fetch={pager => this.fetchTable(pager)} />
				</Modal>
				<div style={{width:'100%'}}>
					<div >
						<div style={{width:'100%'}}>
							<div style={{width:'100%',marginTop:25,marginBottom:25}}>
								<Row style={{width:800,margin:'0 auto',fontSize:16,fontWeight:600}} gutter={24}>
									<Col span={12}>设备编号：{obj.equCode}</Col>
									<Col span={12}>设备名称：{obj.equName}</Col>
								</Row>
							</div>
							<div style={{width:1400,margin:'0 auto'}}>
								<Button icon="plus" type="primary" onClick={this.chooseEqu}>选择设备</Button>
								<Table columns={columns} rowKey={(record, index) => index} dataSource={equipmentRepairWorkAddDTOList} pagination={false} loading={loading} scroll={{ y: 450 ,x:1200}} />
							</div>
						</div>
						<div style={{width:'100%',marginTop:100}}>
							<div style={{margin:'0 auto',width:'400px'}}>
								<Button icon="check" onClick={this.handleSubmit} type="primary" style={{marginRight: 38,}}>保存</Button>
								<Button onClick={()=>{this.props.history.push('/EquipmentList')}} icon="close">取消</Button>
							</div>
						</div>
					</div>
				</div>
			</div>
		 );
	 }
 }
 export default Form.create()(withRouter(App));
 